<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="场地名称" prop="deptName">
                <el-input
                    v-model="queryParams.search"
                    placeholder="请输入场地名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="所属单位：" prop="company_id">
                <el-select v-model="queryParams.company_id"  placeholder="请选择单位" size="small"  >
                    <el-option v-for="(item, index) in companyList" :key="index" :label="item.company_name"
                               :value="item.company_id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="状态" clearable>
                    <el-option
                        v-for="dict in dict.type.sys_normal_disable"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table  v-loading="loading" :data="Lists" border fit highlight-current-row>
            <el-table-column type="selection" width="55" bo align="center" label-width="100px" />
            <el-table-column label="编号" align="center" prop="site_id"/>
            <el-table-column label="场地名称" align="center" prop="site_name" />
            <el-table-column label="场地位置" align="center" prop="address" />
            <el-table-column label="场地联系人" align="center" prop="site_user_name"/>
            <el-table-column label="场地联系人方式" align="center" prop="mobile" />
            <el-table-column label="所属单位" align="center" prop="company_id" >
                <template slot-scope="{row}">
                    {{ row.company_info? row.company_info.company_name : "" }}
                </template>
            </el-table-column>
            <el-table-column  label="状态" prop="status" align="center" width="100">
                <template slot-scope="{row}">
                    <dict-tag :options="dict.type.sys_normal_disable" :value="row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                <template slot-scope="{row}">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(row)"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.limit"
            @pagination="getList"
        />

        <!-- 添加或修改部门对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
            <el-row border :gutter="15" class="">
                <el-col :span="14">
                    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                        <el-form-item label="场地名称" prop="site_name">
                            <el-input v-model="form.site_name" placeholder="请输入场地名称" />
                        </el-form-item>
                        <el-form-item label="所属单位：" prop="company_id">
                            <el-select v-model="form.company_id"  placeholder="请选择单位 " size="small"  >
                                <el-option v-for="(item, index) in companyList" :key="index" :label="item.company_name"
                                           :value="item.company_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="场地编码" prop="site_code">
                            <el-input v-model="form.site_code" placeholder="请输入场地编码" />
                        </el-form-item>
                        <el-form-item label="场地位置" prop="address">
                            <el-input v-model="form.address" placeholder="请输入场地位置" />
                        </el-form-item>
                        <el-form-item label="场地面积" prop="area_size">
                            <el-input v-model="form.area_size" placeholder="请输入场地面积" />
                        </el-form-item>
                        <el-form-item label="联系人" prop="site_user_name">
                            <el-input v-model="form.site_user_name" placeholder="请输入场地联系人" />
                        </el-form-item>
                        <el-form-item label="联系人电话" prop="mobile">
                            <el-input v-model="form.mobile" placeholder="请输入场地联系人电话" />
                        </el-form-item>
                        <el-form-item label="基准租金单价" prop="rental_price">
                            <el-input v-model="form.rental_price" placeholder="请输入基准租金单价(元/m²/月)" />
                        </el-form-item>

                        <el-form-item label="经度" prop="kqLongitude">
                            <el-input v-model="form.lng" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="纬度" prop="kqLatitude">
                            <el-input v-model="form.lat" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                    v-for="dict in dict.type.sys_normal_disable"
                                    :key="dict.value"
                                    :label="dict.value"
                                >{{dict.label}}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="10">
                    <div class="search_box">
                        <div class="label">关键字搜索</div>
                        <el-input v-model="form.address" placeholder="请输入内容" id="tipinput"></el-input>
                    </div>
                    <div ref="gaode_Map" id="gaode_Map" ></div>
                </el-col>
            </el-row>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>

import {getSiteList,createSite,updateSite,getSiteDetail,delSite} from "@/api/system/site";

import {getMasterList,createMaster,updateMaster,getMasterDetail,changeFiledStatus,delMaster} from "@/api/expenses/master.js";
import { getCompanySelectList} from "@/api/system/company";
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
    // 设置安全密钥
    securityJsCode: "2353313c155de6c8befa6921880c92fe",
};

export default {
    name: "site",
    dicts:['sys_normal_disable'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 表格数据
            Lists: [],
            companyList: [],//单位
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否展开，默认全部展开
            isExpandAll: true,
            // 重新渲染表格状态
            refreshTable: true,
            // 查询参数
            queryParams: {
                search: undefined,
                company_id: undefined,
                status: undefined,
                page: 1,
                limit: 10,
            },
            // 表单参数
            form: {},
            input: "",
            map: null,
            autoAMap: null,

            placeSearch: null,
            markers: [],
            position: {},
            AMapPluyins: ["AMap.Geolocation","AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder","AMap.ControlBar"],
            longitude:"",
            latitude:"",
            lnglat: [],
            // 表单校验
            rules: {
                company_id: [
                    { required: true, message: "请选择单位", trigger: "blur" }
                ],
                site_name: [
                    { required: true, message: "请选择水机", trigger: "blur" }
                ],
                area_size: [
                    { required: true, message: "场地面积不能为空", trigger: "blur" }
                ],
                rental_price: [
                    { required: true, message: "场地租金单价  不能为空", trigger: "blur" }
                ],
                site_user_name: [
                    { required: true, message: "场地名称不能为空", trigger: "blur" }
                ],
                mobile: [
                    { required: true, message: "场地联系人方式不能为空", trigger: "blur" }
                ],
                address: [
                    { required: true, message: "场地位置不能为空", trigger: "blur" }
                ],
            },

        };
    },
    created() {
        this.getList();
        this.getCompany();
    },
    methods: {
        /** 查询部门列表 */
        async getList() {
            let that = this;
            that.loading = true;
            const {data, status, msg} = await getSiteList(this.queryParams);
            that.Lists = data.data;
            that.loading = false;
            that.total = data.total;
            that.queryParams.limit = data.per_page || 10;

        },
        //片区
        async getCompany() {
            const res = await getCompanySelectList();
            this.companyList = res.data;
            console.log("this.companyList",this.companyList)
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                site_id: undefined,
                company_id: undefined,
                site_name: undefined,
                site_code: undefined,
                area_size: undefined,
                site_sn: undefined,
                rental_price: undefined,
                province_id: undefined,
                city_id: undefined,
                district_id: undefined,
                address: undefined,
                lng: undefined,
                lat: undefined,
                remark: undefined,
                status: "1"
            };
            this.resetForm("form");
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd(row) {
            this.reset();
            this.open = true;
            this.lnglat = []
            this.title = "添加数据";

            this.initMap()
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const site_id = row.site_id || this.ids
            getSiteDetail({site_id:site_id}).then(response => {
                let data= response.data;
                this.form = data;
                this.form.status = data.status.toString();
                this.open = true;
                this.lnglat=[data.lng,data.lat];
                this.title = "修改";
                this.initMap()
            });
        },
        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.site_id != undefined) {
                        updateSite(this.form).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        createSite(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.confirm('是否确认删除名称为"' + row.meter_name + '"的数据项？').then(function() {
                return delMaster({read_id:row.read_id});
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => {});
        },
        /**加载地图*/
        initMap () {
            let centerLen = [116.397428, 39.90923];
            AMapLoader.load({
                key: "86df05c4db672bcbfabc7c71226a5c0a", // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: this.AMapPluyins,
            }).then((AMap) => {
                this.map = new AMap.Map("gaode_Map", {
                    // 设置地图容器id
                    viewMode: "3D", //  是否为3D地图模式
                    zoom: 18, // 初始化地图级别
                    center: centerLen, //中心点坐标
                    resizeEnable: true,
                });
                this.setMarker(centerLen)
                // 关键字查询
                this.searchMap();
                // 监听鼠标点击事件
                this.map.on("click", this.clickMapHandler);
            })
                .catch((e) => { });
        },
        // 关键字查询
        searchMap () {
            // 搜索框自动完成类
            this.autoAMap = new AMap.AutoComplete({
                input: "tipinput", // 使用联想输入的input的id
            });
            //构造地点查询类
            this.placeSearch = new AMap.PlaceSearch({
                map: this.map,
            });
            // 当选中某条搜索记录时触发
            this.autoAMap.on("select", this.selectSite);
        },
        //选中查询出的记录
        selectSite (e) {
            if (e.poi.location) {
                this.placeSearch.setCity(e.poi.adcode);
                this.placeSearch.search(e.poi.name); //关键字查询
                let geocoder = new AMap.Geocoder({});
                let that = this;
                geocoder.getAddress(this.form.lnglat, function (status, result) {
                    console.log('选中查询出的记录',result)
                    if (status === "complete" && result.regeocode) {
                        that.province = result.regeocode.addressComponent.province;
                        that.city = result.regeocode.addressComponent.city;
                        //自己想要赋的值，根据自己的做修改
                        that.$set(that.form, "province", that.province);
                        that.$set(that.form, "city", that.city);
                        that.$set(that.form, "address", e.poi.name);
                        that.$set(
                            that.form,
                            "coordinate",
                            e.poi.location.lng + "," + e.poi.location.lat
                        ); //纬度，经度
                    } else {
                    }
                });
            } else {
                this.$message.error("查询地址失败，请重新输入地址");
            }
        },
        // 点击地图事件获取经纬度，并添加标记
        clickMapHandler (e) {
            this.form.lng = e.lnglat.getLng();
            this.form.lat = e.lnglat.getLat();
            this.lnglat = [e.lnglat.getLng() , e.lnglat.getLat()];

            this.setMarker(this.lnglat);
            // 点击地图上的位置，根据经纬度转换成详细地址
            let geocoder = new AMap.Geocoder({});
            let that = this;
            geocoder.getAddress(this.lnglat, function (status, result) {
                console.log("点击",result)
                if (status === "complete" && result.regeocode) {
                    that.form.address = result.regeocode.formattedAddress;
                } else {
                }
            });
            this.position = {
                longitude: e.lnglat.getLng(),
                latitude: e.lnglat.getLat(),
                address: that.address,
            };
            this.form.address= that.address; //把查询到的地址赋值到输入框
        },
        //  添加标记
        setMarker (lnglat) {
            this.removeMarker();
            let marker = new AMap.Marker({
                position: lnglat,
            });
            marker.setMap(this.map);
            this.markers.push(marker);
        },
        // 删除之前后的标记点
        removeMarker () {
            if (this.markers) {
                this.map.remove(this.markers);
            }
        },
    }
};
</script>
<style>
#gaode_Map {
    overflow: hidden;
    width: 100%;
    height: 500px;
    margin: 0;
}.amap-sug-result {
     z-index: 2999 !important;
 }
</style>
